This article will show you how to report XML data with
Crystal Reports and Windows Forms client.
Following is the partial listing from the sample XML file which I am using in the demo:
<Student>
<Name>Rohit Kesharwani</Name> <Course>GNIIT</Course>
<Age>20</Age>
<Hobby>Cricket</Hobby>
</Student>
Add a DataSet to the project. Select Add -> New Item -> DataSet from Solution Explorer.
Add DataTable to DataSet from the toolbox. Now add columns to the DataTable
Right-click on DataTable1 and select Add -> Column to start adding the columns to the DataTable.
Now add a DataSet as a source of data for a report. You’ll start with Right-Clicking on any open area on Report Designer -> Database -> Database Expert…
As a result of this action, the Database Expert dialog box will appear. You can click on Project Data and expand the node ADO.NET DataSet.
Select the DataTable from DataSet and click on the “>” button to move it to the selected tables section on the right-hand side.
Once the report source is specified, all we have to do is drag and drop the fields from DataTable inside Detail section on report designer surface.
You can drag and drop all the fields from DataTable from Field Explorer inside the details section.
You can add a crystalReportViewer to the Form1 as follows:
Drag ToolBox -> Reporting -> CrystalReportViewer and drop it on Form1. This step
will create a new instance of crystalReportViewer with the name
crystalReportViewer1.
After the design part, add code in the Form.cs to read the xml data in the Dataset.
private void Form1_Load(object sender, EventArgs e)
{
try
{
DataSet dsSet = new DataSet();
dsSet.Tables.Add("DataTable1");
//create temp dataset to read xml data
DataSet dsTempReport = new DataSet();
// using ReadXml method of DataSet read XML data from Student.xml file
dsTempReport.ReadXml(@"D:\rohit\Student.xml");
// copy XML data from temp dataset to our typed data set
dsSet.Tables[0].Merge(dsTempReport.Tables[0]);
//prepare report for preview
CrystalReport1 rptXml = new CrystalReport1();
rptXml.SetDataSource(dsSet.Tables[0]);
crystalReportViewer1.ShowGroupTreeButton = false;
crystalReportViewer1.ReportSource = rptXml;
} catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Let’s build and run the example to see the output.
Leave Comment